package com.swift.violent.mainstay.config.expand;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.github.alenfive.rocketapi.entity.ApiExample;
import com.github.alenfive.rocketapi.entity.ApiInfo;
import com.github.alenfive.rocketapi.extend.IApiDocSync;
import com.swift.violent.mainstay.common.constants.Global;
import com.swift.violent.mainstay.common.constants.ResultDesc;
import com.swift.violent.mainstay.core.api.core.modal.dto.ShowDocUpdateApi;
import com.swift.violent.mainstay.core.api.core.service.ApiDocSync;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.beetl.core.resource.ClasspathResourceLoader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 文档同步
 *
 * @author xuhaifeng
 * @date 2021.1.19 23:13
 */
@Slf4j
@Component
@SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection")
public class DefaultApiDocSync implements IApiDocSync {
    @Autowired
    private ApiDocSync apiDocSync;
    private static final String NOT_CONFIGURED = "未配置";
    /**
     * api秘钥
     */
    private static final String API_KEY = "03cb28f7aa504aac26636433356d63ee189721877";
    /**
     * api象征
     */
    private static final String API_TOKEN = "43e8ffa2b6c9338132330b33eb643c43511440429";

    @Override
    public String sync(ApiInfo apiInfo, ApiExample apiExample) {
        if (Objects.nonNull(apiExample)) {
            final String name = apiInfo.getName();
            apiDocSync.showDocSync(JSON.parseObject(JSON.toJSONString(ShowDocUpdateApi.builder()
                    .apiKey(API_KEY)
                    .apiToken(API_TOKEN)
                    .catName(apiInfo.getGroupName())
                    .pageTitle(StrUtil.isNotEmpty(name) ? name : NOT_CONFIGURED)
                    .pageContent(apiDocContentConstruction(apiInfo, apiExample))
                    .build())));
        }
        return ResultDesc.OK.toString();
    }

    /**
     * api文档生成
     *
     * @param apiInfo    api信息
     * @param apiExample api范例
     *
     * @return api文档
     */
    @SneakyThrows
    private String apiDocContentConstruction(ApiInfo apiInfo, ApiExample apiExample) {
        final Template t = new GroupTemplate(new ClasspathResourceLoader(), Configuration.defaultConfiguration())
                .getTemplate("/template/apiDocTemplate.btl");
        final String options = apiInfo.getOptions();
        final JSONObject jsonOption = JSON.parseObject(options);
        jsonOption.remove("hasRole");
        jsonOption.remove("hasPermi");
        jsonOption.remove("lacksRole");
        jsonOption.remove("lacksPermi");
        jsonOption.remove("hasAnyPermi");
        jsonOption.remove("hasAnyRoles");
        t.binding("remark", Global.NOT);
        t.binding("requestUrl", apiExample.getUrl());
        t.binding("briefDescription", apiInfo.getName());
        t.binding("requestMethod", apiExample.getMethod());
        t.binding("requestExample", jsonFormat(JSON.toJSONString(jsonOption)));
        t.binding("requestHeader", jsonFormat(apiExample.getRequestHeader()));
        t.binding("responseExample", jsonFormat(apiExample.getResponseBody()));
        t.binding("responseHeader", jsonFormat(apiExample.getResponseHeader()));
        t.binding("requestExampleList", jsonOption.keySet());
        return t.render();
    }

    /**
     * json格式化
     *
     * @param jsonString 格式化内容
     *
     * @return 格式化后的json
     */
    private String jsonFormat(final String jsonString) {
        return JSON.toJSONString(JSONObject.parseObject(jsonString),
                SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteDateUseDateFormat);
    }

}